package com.czmh.etc.onlinepubsys.controller.mingchuang;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czmh.etc.common.core.annotation.ApiVersion;
import com.czmh.etc.common.core.utils.JwtUtil;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.constants.mingchuang.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.ApplyInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CarInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.feign.newrun.constans.UserProperty;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult;
import com.czmh.etc.onlinepubsys.jy.utils.PageUtils;
import com.czmh.etc.onlinepubsys.jy.utils.Query;
import com.czmh.etc.onlinepubsys.model.*;
import com.czmh.etc.onlinepubsys.request.mingchuang.*;
import com.czmh.etc.onlinepubsys.services.*;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICarInfoService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcApplyService;
import com.czmh.etc.onlinepubsys.utils.DatetimeUtil;
import com.czmh.etc.onlinepubsys.utils.JsonResultUtil;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.czmh.etc.onlinepubsys.utils.mingchuang.ETCDataEncUtil;
import com.czmh.etc.onlinepubsys.utils.mingchuang.HttpUtil;
import com.czmh.etc.onlinepubsys.utils.mingchuang.PayUtil;
import com.czmh.etc.onlinepubsys.utils.mingchuang.ReqUtil;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.pay.WeixinPayProxy;
import com.foxinmy.weixin4j.pay.model.WeixinPayAccount;
import com.foxinmy.weixin4j.pay.payment.mch.CorpPayment;
import com.foxinmy.weixin4j.pay.payment.mch.CorpPaymentRecord;
import com.foxinmy.weixin4j.pay.payment.mch.CorpPaymentResult;
import com.foxinmy.weixin4j.pay.type.mch.CorpPaymentCheckNameType;
import com.foxinmy.weixin4j.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/{version}/api/mingchang/etc")
@Api(tags = "ETC接口【新】- 铭创")
public class EtcController {
    @Autowired
    private UserProperty userProperty;

    @Autowired
    private ICurrentContextService currentContextService;
    @Autowired
    private IEtcApplyService etcApplyService;
    @Autowired
    private ICarInfoService carInfoService;
    @Autowired
    private EtcOrderService orderService;
    @Autowired
    private EtcCancelService etcCancelService;
    @Autowired
    private EtcRewardService etcRewardService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private EtcReplaceService etcReplaceService;

    @Autowired
    private EtcAfterSaleDeviceService etcAfterSaleDeviceService;


    @Value("${mingchuang.url}")
    private String url0;
    @Value("${mingchuang.accessKey}")
    private String accessKey0;
    @Value("${mingchuang.signature}")
    private String signature0;

    @Value("${wx.certpath}")
    private String certPath;

    @Value("${wx.wxPayMch_id}")
    private String wxPayMchId;

    @Value("${wx.wxPayAppSecret}")
    private String wxPayAppSecret;

    @Value("${wx.wxPayAppid}")
    private String appId;


    @PostMapping("/updateStatus")
    @ApiOperation("ETC申请状态变更，从2->1")
    public JSONResult updateStatus(@RequestBody EtcApplyReqest req) {
        log.info("ETC申请状态变更:{}", JSON.toJSONString(req));
        JSONResult result = new JSONResult();
        result.setCode(JSONResult.SUCCESS);
        result.setCurrentTime(System.currentTimeMillis());
        CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
        if (ctx == null) {
            result.setCode(JSONResult.FAIL);
            result.setCurrentTime(System.currentTimeMillis());
            result.setMessage("该用户不在申办流程当中！");
        } else {
            if (ctx.getState() != 2) {
                result.setCode(JSONResult.FAIL);
                result.setCurrentTime(System.currentTimeMillis());
                result.setMessage("该用户已提交车辆信息，" + ctx.getState());
                return result;
            } else {
                ctx.setState(1);
                currentContextService.update(ctx);
            }
        }
        return result;
    }

    @PostMapping("/apply")
    @ApiOperation("ETC申请 1194")
    public JSONResult apply(@RequestBody EtcApplyReqest req) {
        log.info("ETC申请:{}", JSON.toJSONString(req));

        String userId = req.getUserId();
        req.setClientNo(userProperty.getClientNo()); //设置网点编号
        req.setOptBy(userProperty.getOptBy()); //设置操作员
        JSONResult result = HttpUtil.post(BusinessType.ETC_APPLY, req);
        if (result.getCode().equals(JSONResult.SUCCESS)) {
            String fundAccountId = JSON.parseObject(result.getRspData()).getString("fundAccountId");

            log.info("保存ETC申请信息:资金账号:{}", fundAccountId);
            CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
            //处理用户上传的图片信息
            ApplyExtInfo applyExtInfo = req.getApplyExtInfo();
            if (applyExtInfo != null) {
                applyExtInfo.setAgentBackImgUrl(applyExtInfo.getAgentBackImgUrl());
                applyExtInfo.setAgentFrontImgUrl(applyExtInfo.getAgentFrontImgUrl());
                applyExtInfo.setCertImgUrl(applyExtInfo.getCertImgUrl());
            }

            if (StringUtils.isNotEmpty(ctx.getApplyId())) {
                ApplyInfo applyInfo = etcApplyService.get(ctx.getApplyId());
                if (null != applyInfo) {
                    ApplyInfo applyInfo1 = new ApplyInfo(null, userId, "", req.getAccountName(),
                            req.getOwnerType(), req.getCertifiType(), req.getCertifiNo(), req.getAgentIdNum(), req.getMobile(), req.getDepartment(),
                            req.getAgentFrontImg(), req.getAgentBackImg(), req.getCertImg(), req.getEnterpriseName(),
                            req.getEnterpriseNo(), null, null, null, null,
                            null, ctx.getOrderNo(), null, null, 0, null, 0, applyExtInfo == null ? null : JSON.toJSONString(applyExtInfo));
                    applyInfo1.setId(applyInfo.getId());
                    etcApplyService.update(applyInfo1);
                    ctx.setApplyId(applyInfo.getId());
                } else {
                    result.setCode(JSONResult.FAIL);
                    result.setCurrentTime(System.currentTimeMillis());
                    result.setMessage("用户车辆信息缺失，请联系管理员！");
                }
            } else {
                ApplyInfo applyInfo = new ApplyInfo(null, userId, "", req.getAccountName(),
                        req.getOwnerType(), req.getCertifiType(), req.getCertifiNo(), req.getAgentIdNum(), req.getMobile(), req.getDepartment(),
                        req.getAgentFrontImg(), req.getAgentBackImg(), req.getCertImg(), req.getEnterpriseName(),
                        req.getEnterpriseNo(), null, null, null, null,
                        null, ctx.getOrderNo(), null, null, 0, null, 0, applyExtInfo == null ? null : JSON.toJSONString(applyExtInfo));
                etcApplyService.save(applyInfo);
                ctx.setApplyId(applyInfo.getId());
            }

            //更新进行时
            ctx.setFundAccountId(fundAccountId);
            ctx.setState(2); //已提交申请
            currentContextService.update(ctx);
        }
        return result;
    }

    @PostMapping("/activeApply")
    @ApiOperation("ETC激活申请 1070")
    public JSONResult activeApply(@RequestBody EtcActiveApplyRequest req) {
        log.info("ETC激活申请:{}", JSON.toJSONString(req));

        String userId = req.getVehicle().getUserId();
        CurrentContext ctx = currentContextService.getByUserId(userId);

        //更新用户ETC卡信息到流程信息当中，方便后面激活后把信息同步到obu数据表
        ctx.setBeginTime(req.getStartTime());
        ctx.setEndTime(req.getEndTime());
        currentContextService.update(ctx);

        CarInfo carInfo = carInfoService.get(ctx.getCarId());
        ApplyInfo applyInfo = etcApplyService.get(ctx.getApplyId());

        req.setSignChannelId(ctx.getSignChannelId());
        req.setFundAccountId(ctx.getFundAccountId());
        req.setOptBy(userProperty.getOptBy());
        req.setClientNo(userProperty.getClientNo());
        req.setVehicle(carInfo);
        req.setDepartment(applyInfo.getDepartment());
        return HttpUtil.post(BusinessType.ETC_ACTIVE_APPLY, req);
    }

    @PostMapping("/dataEnc")
    @ApiOperation("ETC卡数据加密 1003")
    public JSONResult dataEnc(@RequestBody EtcDataEncRequest req) {
        log.info("ETC卡数据加密:{}", JSON.toJSONString(req));
        String data = null;
        req.setClientNo(userProperty.getClientNo());
        CurrentContext ctx = currentContextService.getByUserId(req.getUserId());

        ApplyInfo applyInfo = etcApplyService.get(ctx.getApplyId());

        if (req.getType() == 15) {
            data = ETCDataEncUtil.enc15FileData(req.getData(), req.getBeginDate(), req.getEndDate(),
                    applyInfo.getVehiclePlate(), req.getUserType(), applyInfo.getVehicleColor(),
                    applyInfo.getVehicleType());
            ctx.setBeginDate(req.getBeginDate());
            ctx.setEndDate(req.getEndDate());
            currentContextService.update(ctx);
        } else if (req.getType() == 16) {
            data = ETCDataEncUtil.enc16FileData(applyInfo.getUsername(), applyInfo.getCertifiNo(),
                    applyInfo.getCertifiType());
        }
        req.setData(data);
        return HttpUtil.post(BusinessType.ETC_DATA_ENC, req);
    }

    @PostMapping("/etcCardCancel")
    @ApiOperation("ETC销卡业务 1080")
    public JSONResult etcCardCancel(@RequestBody EtcCardCancelRequest req, HttpServletRequest request) {
        JSONResult jsonResult = new JSONResult();
        //检查用户有效性
        try {
            if (req.getUserId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("用户ID不能为空");
                return jsonResult;
            }
            if (req.getOrderId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("订单ID不能为空");
                return jsonResult;
            }
            if (req.getEcardNo() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("ETC卡号不能为空");
                return jsonResult;
            }
            if (StringUtils.isEmpty(ReqUtil.getToken(request))) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("token不能为空");
                return jsonResult;
            }
            if (JwtUtil.checkToken(req.getUserId(), ReqUtil.getToken(request))) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("用户校验异常");
                return jsonResult;
            }
/*            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("obuDeviceSn", req.getObuId());
            EtcDevice etcDevice = orderService.queryObject(queryMap);
            if(etcDevice == null){
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("OBU设备不存在！");
                return jsonResult;
            }*/

        } catch (Exception e) {
            e.printStackTrace();
            log.info("OBU注销业务-用户校验异常");
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("请求数据校验异常！");
            return jsonResult;
        }
        //检查订单设备是否激活
        QueryWrapper<ApplyInfo> infoQueryWrapper = new QueryWrapper();
        infoQueryWrapper.eq("orderNo", req.getOrderId());
        ApplyInfo applyInfo = etcApplyService.queryObject(infoQueryWrapper);
        if (applyInfo == null) {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("设备不存在！");
            return jsonResult;
        }
        if (applyInfo != null && applyInfo.getState() == 2) {
            req.setOptBy(userProperty.getOptBy());
            req.setClientNo(userProperty.getClientNo());
            //判断之前是否提交过申请
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("type", "1");
            queryMap.put("orderId", req.getOrderId());
            queryMap.put("content", req.getEcardNo());
            queryMap.put("stateNotIn", "2");
            int c = etcCancelService.queryTotal(queryMap);
            if (c > 0) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("请不要重复提交注销申请！");
                return jsonResult;
            } else {
                //保存注销数据提交后台待审核
                Date date = new Date();
                EtcCancel etcCancel = new EtcCancel();
                etcCancel.setDeleteFlag(0);
                etcCancel.setCreateTime(date);
                etcCancel.setUpdatedTime(date);
                etcCancel.setCreateUserId(req.getUserId());
                etcCancel.setImages(req.getImages());
                etcCancel.setReason(req.getRemark());
                etcCancel.setReqData(JSON.toJSONString(req));
                etcCancel.setId(Sequence.getId());
                etcCancel.setOrderId(req.getOrderId());
                etcCancel.setContent(req.getEcardNo());
                etcCancel.setUserId(req.getUserId());
                etcCancel.setState(1);
                etcCancel.setUserId(req.getUserId());
                etcCancel.setType(1);
                int r = etcCancelService.saveSelective(etcCancel);
                if (r > 0) {
                    jsonResult.setCode(JSONResult.SUCCESS);
                    jsonResult.setCurrentTime(System.currentTimeMillis());
                    jsonResult.setMessage("注销申请提交成功！");
                    return jsonResult;
                } else {
                    jsonResult.setCode(JSONResult.FAIL);
                    jsonResult.setCurrentTime(System.currentTimeMillis());
                    jsonResult.setMessage("注销申请提交失败！");
                    return jsonResult;
                }
            }
        } else {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("设备未激活！");
            return jsonResult;
        }
        //return HttpUtil.post(BusinessType.ETC_CARD_CANCEL, req);
    }

    @PostMapping("/obuCancel")
    @ApiOperation("OBU注销业务 1150")
    public JSONResult obuCancel(@RequestBody ObuCancelRequest req, HttpServletRequest request) {
        JSONResult jsonResult = new JSONResult();
        //检查用户有效性
        try {
            if (req.getUserId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("用户ID不能为空");
                return jsonResult;
            }
            if (req.getOrderId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("订单ID不能为空");
                return jsonResult;
            }
            if (req.getObuId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("OBU编号不能为空");
                return jsonResult;
            }
            if (StringUtils.isEmpty(ReqUtil.getToken(request))) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("token不能为空");
                return jsonResult;
            }
            if (JwtUtil.checkToken(req.getUserId(), ReqUtil.getToken(request))) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("用户校验异常");
                return jsonResult;
            }
/*            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("obuDeviceSn", req.getObuId());
            EtcDevice etcDevice = orderService.queryObject(queryMap);
            if(etcDevice == null){
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("OBU设备不存在！");
                return jsonResult;
            }*/

        } catch (Exception e) {
            e.printStackTrace();
            log.info("OBU注销业务-用户校验异常");
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("请求数据校验异常！");
            return jsonResult;
        }
        //检查订单设备是否激活
        QueryWrapper<ApplyInfo> infoQueryWrapper = new QueryWrapper();
        infoQueryWrapper.eq("orderNo", req.getOrderId());
        ApplyInfo applyInfo = etcApplyService.queryObject(infoQueryWrapper);
        if (applyInfo == null) {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("设备不存在！");
            return jsonResult;
        }
        if (applyInfo != null && applyInfo.getState() == 2) {
            req.setOptBy(userProperty.getOptBy());
            req.setClientNo(userProperty.getClientNo());
            req.setOptBy(userProperty.getOptBy());
            req.setClientNo(userProperty.getClientNo());
            //判断之前是否提交过申请
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("type", "2");
            queryMap.put("orderId", req.getOrderId());
            queryMap.put("content", req.getObuId());
            queryMap.put("stateNotIn", "2");
            int c = etcCancelService.queryTotal(queryMap);
            if (c > 0) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("请不要重复提交注销申请！");
                return jsonResult;
            } else {
                //保存注销数据提交后台待审核
                Date date = new Date();
                EtcCancel etcCancel = new EtcCancel();
                etcCancel.setDeleteFlag(0);
                etcCancel.setCreateTime(date);
                etcCancel.setUpdatedTime(date);
                etcCancel.setCreateUserId(req.getUserId());
                etcCancel.setImages(req.getImages());
                etcCancel.setReason(req.getRemark());
                etcCancel.setReqData(JSON.toJSONString(req));
                etcCancel.setId(Sequence.getId());
                etcCancel.setOrderId(req.getOrderId());
                etcCancel.setContent(req.getObuId());
                etcCancel.setUserId(req.getUserId());
                etcCancel.setState(1);
                etcCancel.setType(2);
                int r = etcCancelService.saveSelective(etcCancel);
                if (r > 0) {
                    jsonResult.setCode(JSONResult.SUCCESS);
                    jsonResult.setCurrentTime(System.currentTimeMillis());
                    jsonResult.setMessage("注销申请提交成功！");
                    return jsonResult;
                } else {
                    jsonResult.setCode(JSONResult.FAIL);
                    jsonResult.setCurrentTime(System.currentTimeMillis());
                    jsonResult.setMessage("注销申请提交失败！");
                    return jsonResult;
                }
            }
        } else {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("设备未激活！");
            return jsonResult;
        }
        //return HttpUtil.post(BusinessType.OBU_CANCEL, req);
    }

    @PostMapping("/etcCancel")
    @ApiOperation("ETC注销业务，先操作OBU注销再操作ETC卡注销")
    public JSONResult etcCancel(@RequestBody EtcCancelRequest req, HttpServletRequest request) {
        JSONResult jsonResult = new JSONResult();
        //检查用户有效性
        try {
            if (req.getUserId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("用户ID不能为空");
                return jsonResult;
            }
            if (req.getOrderId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("订单ID不能为空");
                return jsonResult;
            }
            if (req.getObuId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("OBU编号不能为空");
                return jsonResult;
            }
            if (StringUtils.isEmpty(ReqUtil.getToken(request))) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("token不能为空");
                return jsonResult;
            }
            if (JwtUtil.checkToken(req.getUserId(), ReqUtil.getToken(request))) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("用户校验异常");
                return jsonResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("OBU注销业务-用户校验异常");
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("请求数据校验异常！");
            return jsonResult;
        }
        //检查用户有效性
        try {
            if (req.getUserId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("用户ID不能为空");
                return jsonResult;
            }
            if (req.getOrderId() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("订单ID不能为空");
                return jsonResult;
            }
            if (req.getEcardNo() == null) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("ETC卡号不能为空");
                return jsonResult;
            }
            if (StringUtils.isEmpty(ReqUtil.getToken(request))) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("token不能为空");
                return jsonResult;
            }
            if (JwtUtil.checkToken(req.getUserId(), ReqUtil.getToken(request))) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("用户校验异常");
                return jsonResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("OBU注销业务-用户校验异常");
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("请求数据校验异常！");
            return jsonResult;
        }
        //检查订单设备是否激活
        QueryWrapper<ApplyInfo> infoQueryWrapper = new QueryWrapper();
        infoQueryWrapper.eq("orderNo", req.getOrderId());
        ApplyInfo applyInfo = etcApplyService.queryObject(infoQueryWrapper);
        if (applyInfo == null) {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("设备不存在！");
            return jsonResult;
        }
        //检查订单设备是否激活
        QueryWrapper<ApplyInfo> infoQueryWrapper1 = new QueryWrapper();
        infoQueryWrapper1.eq("orderNo", req.getOrderId());
        ApplyInfo applyInfo1 = etcApplyService.queryObject(infoQueryWrapper1);
        if (applyInfo1 == null) {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("设备不存在！");
            return jsonResult;
        }
        if (applyInfo != null && applyInfo.getState() == 2) {
            req.setOptBy(userProperty.getOptBy());
            req.setClientNo(userProperty.getClientNo());
            //判断之前是否提交过申请
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("type", "1");
            queryMap.put("orderId", req.getOrderId());
            queryMap.put("content", req.getEcardNo());
            queryMap.put("stateNotIn", "2");
            int c = etcCancelService.queryTotal(queryMap);
            if (c > 0) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("请不要重复提交注销申请！");
                return jsonResult;
            } else {
            }
        } else {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("设备未激活！");
            return jsonResult;
        }

        if (applyInfo1 != null && applyInfo1.getState() == 2) {
            req.setOptBy(userProperty.getOptBy());
            req.setClientNo(userProperty.getClientNo());
            req.setOptBy(userProperty.getOptBy());
            req.setClientNo(userProperty.getClientNo());
            //判断之前是否提交过申请
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("type", "2");
            queryMap.put("orderId", req.getOrderId());
            queryMap.put("content", req.getObuId());
            queryMap.put("stateNotIn", "2");
            int c = etcCancelService.queryTotal(queryMap);
            if (c > 0) {
                jsonResult.setCode(JSONResult.FAIL);
                jsonResult.setCurrentTime(System.currentTimeMillis());
                jsonResult.setMessage("请不要重复提交注销申请！");
                return jsonResult;
            } else {
            }
        } else {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("设备未激活！");
            return jsonResult;
        }
        //数据入库等待审核
        //保存注销数据提交后台待审核
        Date date = new Date();
        EtcCancel etcCancel = new EtcCancel();
        etcCancel.setDeleteFlag(0);
        etcCancel.setCreateTime(date);
        etcCancel.setUpdatedTime(date);
        etcCancel.setCreateUserId(req.getUserId());
        etcCancel.setImages(req.getImages());
        etcCancel.setRemark(req.getRemark());
        etcCancel.setReqData(JSON.toJSONString(req));
        etcCancel.setId(Sequence.getId());
        etcCancel.setOrderId(req.getOrderId());
        etcCancel.setContent(req.getObuId());
        etcCancel.setState(0);
        etcCancel.setType(2);
        int r = etcCancelService.saveSelective(etcCancel);
        //保存注销数据提交后台待审核
        EtcCancel e = new EtcCancel();
        e.setDeleteFlag(0);
        e.setCreateTime(date);
        e.setUpdatedTime(date);
        e.setCreateUserId(req.getUserId());
        e.setImages(req.getImages());
        e.setRemark(req.getRemark());
        e.setReqData(JSON.toJSONString(req));
        e.setId(Sequence.getId());
        e.setOrderId(req.getOrderId());
        e.setContent(req.getEcardNo());
        e.setState(0);
        e.setType(1);
        int d = etcCancelService.saveSelective(e);
        if (r > 0 && d > 0) {
            jsonResult.setCode(JSONResult.SUCCESS);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("注销申请提交成功！");
            return jsonResult;
        } else {
            etcCancelService.delete(e.getId());
            etcCancelService.delete(etcCancel.getId());
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("注销申请提交失败！");
            return jsonResult;
        }
    }

    /**
     * 分页查询
     */
    @ApiOperation(value = "分页查询", notes = "分页查询", response = EtcObuUser.class)
    @PostMapping("/queryInfoListByType")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "分页数量", required = true, defaultValue = "20"),
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageCount", value = "分页索引", required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型:3微信签约", required = true, paramType = "query", dataType = "String")
    })
    public JSONResult queryInfoListByType(String userId, String type, int pageSize, int pageCount) {
        JSONResult jsonResult = new JSONResult();
        if (StringUtils.isEmpty(userId)) {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("用户ID不能为空！");
            return jsonResult;
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userId", userId);
        queryMap.put("type", type);
        queryMap.put("page", pageCount);
        queryMap.put("limit", pageSize);
        queryMap.put("sidx","obu_create_time desc, card_create_time desc");
        //queryMap.put("order", "obu_create_time desc, card_create_time desc");
        Query query = new Query(queryMap);
        List<EtcObuUser> list = etcCancelService.queryInfoListByType(query);
        int total = etcCancelService.queryInfoTotalByType(query);
        PageUtils pageUtil = new PageUtils(list, total, pageCount, pageSize);
        jsonResult.setCode(JSONResult.SUCCESS);
        jsonResult.setCurrentTime(System.currentTimeMillis());
        jsonResult.setRspData(JSON.toJSONString(pageUtil));
        return jsonResult;
    }

    /**
     * 分页查询
     */
    @ApiOperation(value = "分页查询", notes = "分页查询", response = EtcObuUser.class)
    @PostMapping("/queryInfoList")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "分页数量", required = true, defaultValue = "20"),
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageCount", value = "分页索引", required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query", dataType = "String")
    })
    public JSONResult queryInfoList(String userId, int pageSize, int pageCount) {
        JSONResult jsonResult = new JSONResult();
        if (StringUtils.isEmpty(userId)) {
            jsonResult.setCode(JSONResult.FAIL);
            jsonResult.setCurrentTime(System.currentTimeMillis());
            jsonResult.setMessage("用户ID不能为空！");
            return jsonResult;
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userId", userId);
        queryMap.put("page", pageCount);
        queryMap.put("limit", pageSize);
        queryMap.put("sidx","obu_create_time desc, card_create_time desc");
        //queryMap.put("order", "obu_create_time desc, card_create_time desc");
        Query query = new Query(queryMap);
        List<EtcObuUser> list = etcCancelService.queryInfoList(query);
        int total = etcCancelService.queryInfoTotal(query);

        //以下循环获取设备的换卡签数据
        for (int i = 0; i < list.size(); i++) {
            EtcObuUser etcObuUser = list.get(i);
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", etcObuUser.getOrderId());
            map.put("deleteFlag", "0");
            map.put("activeStatus", "1");
            map.put("sidx", "active_time asc");
            List<EtcAfterSaleDevice> l = etcAfterSaleDeviceService.queryList(map);
            if(CollectionUtils.isNotEmpty(l)){
                for (int j = 0; j < l.size(); j++) {
                    EtcAfterSaleDevice etcAfterSaleDevice = l.get(j);
                    if(etcAfterSaleDevice.getType() == 1){
                        list.get(i).setEtcCardId(etcAfterSaleDevice.getDeviceSn());
                    }
                    if(etcAfterSaleDevice.getType() == 2){
                        list.get(i).setObuId(etcAfterSaleDevice.getDeviceSn());
                    }
                }
            }
        }

        PageUtils pageUtil = new PageUtils(list, total, pageCount, pageSize);
        jsonResult.setCode(JSONResult.SUCCESS);
        jsonResult.setCurrentTime(System.currentTimeMillis());
        jsonResult.setRspData(JSON.toJSONString(pageUtil));
        return jsonResult;
    }

    /**
     * 根据产品编码获取产品激活状态
     *
     * @param productSn 产品编码
     * @return
     */
    @ApiVersion(1)
    @GetMapping("/queryActiveByProductSn")
    @ApiOperation(value = "根据产品编码获取产品激活状态：0未激活或者不存在， 1已激活且允许领取红包和搜索，2本人已领取，3他人已领取 4产品未确认收货，5产品确认收货且未领取红包奖励", notes = "根据产品编码获取产品状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "productSn", value = "产品编码", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "openId", value = "用户openId", required = true)
    })
    public JsonResult queryActiveByProductSn(@RequestParam String productSn, @RequestParam String openId) {
        JsonResult result = new JsonResult();
        JSONObject jsonObject = new JSONObject();
        //获取红包奖励提示
        SysConfig tips  = sysConfigService.queryByKey("reward_tips");
        if(tips != null && tips.getConfigKey() != null && StringUtils.isNotEmpty(tips.getConfigKey())){
            String value = tips.getConfigValue();
            if(StringUtils.isNotEmpty(tips.getConfigValue())){
                jsonObject.put("state", 0);
                result.setData(jsonObject);
                result.setMessage(value);
                result.setCode(JSONResult.FAIL);
                return result;
            }
        }
        //判断黑名单
        SysConfig config = sysConfigService.queryByKey("reward_back_list");
        if(config != null && config.getConfigKey() != null && StringUtils.isNotEmpty(config.getConfigKey())){
            String value = config.getConfigKey();
            if(ArrayUtil.contains(value.split(","), openId)){
                jsonObject.put("state", 0);
                result.setData(jsonObject);
                result.setMessage("您的账号触发了微信风险拦截，当前状态异常无法领取红包！");
                result.setCode(JSONResult.SUCCESS);
                return result;
            }
        }
        if (null == productSn) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("参数异常");
            return result;
        }
        if(productSn.indexOf("XT") > 0){
            int a = productSn.indexOf("XT");
            String s = productSn.substring(a);
            productSn = s;
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("deleteFlag", "0");
        queryMap.put("productSn", productSn);
        queryMap.put("isSearch", "1");
        queryMap.put("isReward", "1");
        EtcDevice etcDevice = orderService.queryObject(queryMap);
        if(etcDevice == null){
            result.setCode(JSONResult.FAIL);
            result.setMessage("产品编码-" + productSn + ",没有红包可领取!");
            return result;
        }
        result.setCode(JSONResult.SUCCESS);
        //判断产品是否有收获确认奖励
        if(etcDevice.getStockMinAmount() > 0 && etcDevice.getStockMaxAmount() > 0){
            //以下通过搜索管理员对应的库存状态是否为确认收货来判断是否发放红包奖励
            Map<String, Object> map = new HashMap<>();
            map.put("deleteFlag", "0");
            map.put("etcObuDeviceSn", etcDevice.getObuDeviceSn());
            map.put("deliveryStatus", "3");
            map.put("customId", "1");
            int l = etcRewardService.queryStockTotal(map);
            if(l == 0){
                jsonObject.put("state", "4");
                result.setData(jsonObject);
                result.setMessage("产品未确认收货！");
                return result;
            }else{
                //通过系统配置信息判断确认收货奖励红包是否失效，失效时间以产品确认收货时间之后15天内有效
                Map<String, Object> param = new HashMap<>();
                param.put("deleteFlag", "0");
                param.put("etcObuDeviceSn", etcDevice.getObuDeviceSn());
                param.put("deliveryStatus", "3");
                param.put("customId", "1");
                param.put("parentCustomId", "1");
                param.put("offset", 0);
                param.put("limit", 1);
                List<EtcStock> etcStocks = etcRewardService.queryStockList(param);
                if(CollectionUtils.isNotEmpty(etcStocks)){
                    EtcStock etcStock = etcStocks.get(0);
                    Date d = new Date();
                    Long longTime = d.getTime();
                    SysConfig sysConfig = sysConfigService.queryByKey("stock_reward_effective_time");
                    if(etcStock.getConfirmTime() != null && sysConfig != null && sysConfig.getConfigKey() != null && Integer.valueOf(sysConfig.getConfigValue()) > 0){
                        if((longTime - etcStock.getConfirmTime().getTime()) >= 60*60*24*1000*Long.valueOf(sysConfig.getConfigValue())){
                            jsonObject.put("state", 0);
                            result.setData(jsonObject);
                            result.setMessage("ETC确认收货后超过" + sysConfig.getConfigValue() + "天未领取，该红包已失效！");
                            result.setCode(JSONResult.FAIL);
                            return result;
                        }
                    }
                }
                Map<String, Object> q = new HashMap<>();
                q.put("deleteFlag", "0");
                q.put("productSn", etcDevice.getProductSn());
                q.put("rewardType", "2");
                List<EtcReward> list = etcRewardService.queryList(q);
                if (CollectionUtils.isNotEmpty(list)) {
                    EtcReward etcReward = list.get(0);
                    if (etcReward != null && etcReward.getStatus() != 0) {
                        //确认红包奖励已经被领取
    //                    result.setCode(JSONResult.FAIL);
    //                    result.setData(etcReward);
    //                    result.setMessage("该红包已经被" + etcReward.getNickname() + "领取，有疑问请联系管理员！");
    //                    return result;
                    }
                }else{
                    jsonObject.put("state", "5");
                    result.setData(jsonObject);
                    result.setMessage("产品已确认收货！");
                    return result;
                }
            }
        }

        //以下判断产品的激活状态
        if (etcDevice == null || etcDevice.getActiveStatus() == 0) {
            jsonObject.put("state", 0);
            result.setData(jsonObject);
            result.setMessage("设备未激活");
        } else if (etcDevice.getActiveStatus() == 1) {
            //判断设备产品是否有激活奖励
            if(etcDevice.getMinAmount() > 0 && etcDevice.getMaxAmount() > 0){
                Map<String, Object> q = new HashMap<>();
                q.put("deleteFlag", "0");
                q.put("rewardType", "1");
                q.put("productSn", etcDevice.getProductSn());
                List<EtcReward> list = etcRewardService.queryList(q);
                if (!CollectionUtils.isEmpty(list)) {
                    EtcReward etcReward = list.get(0);
                    //如果是领奖本人查询信息则直接推送领奖信息
                    if (etcReward.getOpenid().equalsIgnoreCase(openId)) {
                        jsonObject.put("state", 2);
                        result.setMessage("该红包已经被" + etcReward.getNickname() + "领取!!");
                        result.setData(jsonObject);
                    } else {
                        jsonObject.put("state", 3);
                        result.setData(jsonObject);
                        result.setMessage("该红包已经被" + etcReward.getNickname() + "领取!");
                    }
                } else {
                    jsonObject.put("state", 1);
                    result.setData(jsonObject);
                    result.setMessage("设备已激活");
                }
                //通过系统配置信息判断激活奖励红包是否失效，失效时间以产品激活时间之后15天内有效
                Date d = new Date();
                Long longTime = d.getTime();
                SysConfig sysConfig = sysConfigService.queryByKey("active_reward_effective_time");
                if(etcDevice.getActiveTime() != null && sysConfig != null && sysConfig.getConfigKey() != null && Integer.valueOf(sysConfig.getConfigValue()) > 0){
                    if(longTime - etcDevice.getActiveTime().getTime() >= 60*60*24*1000*Long.valueOf(sysConfig.getConfigValue())){
                        jsonObject.put("state", 0);
                        result.setData(jsonObject);
                        result.setMessage("ETC激活后超过" + sysConfig.getConfigValue() + "天未领取，该红包已失效！");
                        result.setCode(JSONResult.FAIL);
                        return result;
                    }
                }
                result.setCode(JSONResult.SUCCESS);
                return result;
            }else{
                jsonObject.put("state", 0);
                result.setData(jsonObject);
                result.setMessage("该产品没有奖励领取！");
                result.setCode(JSONResult.SUCCESS);
                return result;
            }
        }
        jsonObject.put("state", 0);
        result.setData(jsonObject);
        result.setMessage("设备未激活");
        result.setCode(JSONResult.SUCCESS);
        return result;
    }

    /**
     * 提交奖励相关信息
     *
     * @return
     */
    @ApiVersion(1)
    @PostMapping("/submitRewardInfo")
    @ApiOperation(value = "提交奖励相关信息")
    public JsonResult submitRewardInfo(@RequestBody SubmitRewarInfoParam submitRewarInfoParam) {
        log.info("提交奖励相关信息:{}", JSON.toJSONString(submitRewarInfoParam));
        JsonResult result = new JsonResult();
        JSONObject jsonObject = new JSONObject();
        //判断黑名单
        SysConfig config = sysConfigService.queryByKey("reward_back_list");
        if(config != null && config.getConfigKey() != null && StringUtils.isNotEmpty(config.getConfigKey())){
            String value = config.getConfigKey();
            if(ArrayUtil.contains(value.split(","), submitRewarInfoParam.getOpenid())){
                jsonObject.put("state", 0);
                result.setData(jsonObject);
                result.setMessage("您的账号触发了微信风险拦截，当前状态异常无法领取红包！");
                result.setCode(JSONResult.SUCCESS);
                return result;
            }
        }
        String validCode = submitRewarInfoParam.getValidCode();
        String mobile = submitRewarInfoParam.getPhone();
        if (null == submitRewarInfoParam.getProductSn() || StringUtils.isEmpty(mobile) || StringUtils.isEmpty(validCode)) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("参数异常");
            return result;
        }
        // 手机号+验证码登录
        String redisValidCode = String.valueOf(redisUtil.get(mobile));
        if (StringUtils.isNotEmpty(validCode) && StringUtils.isNotEmpty(redisValidCode)
                && (validCode.equals(redisValidCode))) {
            if (!"18520208888".equals(mobile)) {
                // 注销验证码
                redisUtil.del(mobile);
            }
        } else {
            result.setCode(JSONResult.FAIL);
            result.setMessage("手机验证码不正确！");
            return result;
        }
        //判断产品码
        if(submitRewarInfoParam.getProductSn().indexOf("XT") > 0){
            int a = submitRewarInfoParam.getProductSn().indexOf("XT");
            String s = submitRewarInfoParam.getProductSn().substring(a);
            submitRewarInfoParam.setProductSn(s);
        }
        if(submitRewarInfoParam.getRewardType() != null && submitRewarInfoParam.getRewardType() == 2){
            //处理激活奖励
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("productSn", submitRewarInfoParam.getProductSn());
            queryMap.put("isSearch", "1");
            queryMap.put("isReward", "1");
            EtcDevice etcDevice = orderService.queryObject(queryMap);
            result.setCode(JSONResult.SUCCESS);
            if (etcDevice == null) {
                jsonObject.put("state", "0");
                result.setData(jsonObject);
                result.setMessage("设备未激活");
                return result;
            }

            //以下通过搜索管理员对应的库存状态是否为确认收货来判断是否发放红包奖励
            Map<String, Object> map = new HashMap<>();
            map.put("deleteFlag", "0");
            map.put("etcObuDeviceSn", etcDevice.getObuDeviceSn());
            map.put("deliveryStatus", "3");
            map.put("customId", "1");
            int l = etcRewardService.queryStockTotal(map);
            if(l == 0){
                jsonObject.put("state", "0");
                result.setData(jsonObject);
                result.setMessage("产品未确认收货！");
                return result;
            }

            Map<String, Object> q = new HashMap<>();
            q.put("deleteFlag", "0");
            q.put("productSn", submitRewarInfoParam.getProductSn());
            q.put("rewardType", "2");
            List<EtcReward> list = etcRewardService.queryList(q);
            if (CollectionUtils.isNotEmpty(list)) {
                EtcReward etcReward = list.get(0);
                if (etcReward != null && etcReward.getStatus() != 0) {
                    result.setCode(JSONResult.FAIL);
                    result.setData(etcReward);
                    result.setMessage("该红包已经被" + etcReward.getNickname() + "领取，有疑问请联系管理员！!");
                    return result;
                }
            } else {
                //通过系统配置信息判断确认收货奖励红包是否失效，失效时间以产品确认收货时间之后15天内有效
                Map<String, Object> param = new HashMap<>();
                param.put("deleteFlag", "0");
                param.put("etcObuDeviceSn", etcDevice.getObuDeviceSn());
                param.put("deliveryStatus", "3");
                param.put("customId", "1");
                param.put("parentCustomId", "1");
                param.put("offset", 0);
                param.put("limit", 1);
                List<EtcStock> etcStocks = etcRewardService.queryStockList(param);
                if(CollectionUtils.isNotEmpty(etcStocks)){
                    EtcStock etcStock = etcStocks.get(0);
                    Date d = new Date();
                    Long longTime = d.getTime();
                    SysConfig sysConfig = sysConfigService.queryByKey("stock_reward_effective_time");
                    if(etcStock.getConfirmTime() != null && sysConfig != null && sysConfig.getConfigKey() != null && Integer.valueOf(sysConfig.getConfigValue()) > 0){
                        if(longTime - etcStock.getConfirmTime().getTime() >= 60*60*24*1000*Long.valueOf(sysConfig.getConfigValue())){
                            jsonObject.put("state", 0);
                            result.setData(jsonObject);
                            result.setMessage("ETC激活后超过" + sysConfig.getConfigValue() + "天未领取，该红包已失效！");
                            result.setCode(JSONResult.FAIL);
                            return result;
                        }
                    }
                }

                int a = 0;
                try {
                    //转账金额
                    Double amount = 0.0;
                    if (etcDevice.getStockMaxAmount().intValue() == etcDevice.getStockMinAmount()) {
                        amount = DateUtil.formatFee2Yuan(etcDevice.getStockMinAmount());
                    }
                    //如果区间上下限值不同则取区间随机数
                    if (etcDevice.getStockMaxAmount().intValue() != etcDevice.getStockMinAmount()) {
                        int min = etcDevice.getStockMinAmount(), max = etcDevice.getStockMaxAmount();
                        amount = DateUtil.formatFee2Yuan(min + (int) (Math.random() * (max - min + 1)));
                    }
                    //首先插入一条为付款的数据
                    Date date = new Date();
                    EtcReward etcReward = new EtcReward();
                    etcReward.setPayAmount(DateUtil.formatYuan2Fen(amount));
                    etcReward.setId(Sequence.getId());
                    etcReward.setCity(submitRewarInfoParam.getCity());
                    etcReward.setCountry(submitRewarInfoParam.getCountry());
                    etcReward.setProvince(submitRewarInfoParam.getProvince());
                    etcReward.setSubscribe(1);
                    etcReward.setStatus(1);
                    etcReward.setPayStatus(0);
                    etcReward.setLanguage("zh_CN");
                    etcReward.setDeleteFlag(0);
                    etcReward.setRewardType(2);
                    //使用OBU设备的序列号作为商户订单号
                    etcReward.setOrderId(etcDevice.getObuDeviceSn());
                    etcReward.setSubscribeTime(date);
                    etcReward.setUpdatedTime(etcReward.getUpdatedTime());
                    etcReward.setName(submitRewarInfoParam.getName());
                    etcReward.setPhone(submitRewarInfoParam.getPhone());
                    etcReward.setNickname(submitRewarInfoParam.getNickname());
                    etcReward.setSex(submitRewarInfoParam.getSex());
                    etcReward.setStoreAddress(submitRewarInfoParam.getStoreAddress());
                    etcReward.setOpenid(submitRewarInfoParam.getOpenid());
                    etcReward.setUnionid(submitRewarInfoParam.getUnionid());
                    etcReward.setHeadimgurl(submitRewarInfoParam.getHeadimgurl());
                    etcReward.setProductSn(submitRewarInfoParam.getProductSn());
                    etcReward.setCreateTime(date);
                    etcReward.setUpdatedTime(date);
                    etcReward.setRequestData("");
                    etcReward.setRequestData(JSON.toJSONString(etcReward));
                    a = etcRewardService.save(etcReward);
                    if (a > 0) {
                        //插入未付款数据之后开始付款
                        CorpPaymentResult corpPaymentResult = null;
                        try {
                            log.info(JSON.toJSONString(etcReward));
                            corpPaymentResult = sendCorpPayment(etcDevice, etcReward);
                            if (corpPaymentResult != null) {
                                log.info(JSON.toJSONString(corpPaymentResult));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            etcReward.setJsonData(e.getMessage());
                        }
                        //付款失败之后把记录状态改成支付失败，后面允许再次支付
                        if (corpPaymentResult == null) {
                            etcReward.setPayStatus(3);
                            etcReward.setUpdatedTime(new Date());
                        } else if (corpPaymentResult != null && corpPaymentResult.getTransactionId() != null) {
                            //微信付款成功之后改变记录的支付状态，同时更新记录的其他信息
                            etcReward.setPaymentTime(DatetimeUtil.parseSQLDate(corpPaymentResult.getPaymentTime(), DatetimeUtil.STANDARD_DATETIME_PATTERN));
                            etcReward.setPaymentNo(corpPaymentResult.getTransactionId());
                            etcReward.setPayStatus(2);
                            etcReward.setJsonData(JSON.toJSONString(corpPaymentResult));
                            etcReward.setUpdatedTime(new Date());
                            JSONObject json = JSON.parseObject(JSON.toJSONString(corpPaymentResult));
                            json.put("payAmount", etcReward.getPayAmount());
                            result.setData(json);
                        } else {
                            //支付失败之后把记录状态改成支付失败，后面允许再次支付
                            etcReward.setJsonData(JSON.toJSONString(corpPaymentResult));
                            etcReward.setPayStatus(3);
                            etcReward.setUpdatedTime(new Date());
                            result.setData(corpPaymentResult);
                        }
                        //更新记录信息
                        a = etcRewardService.update(etcReward);
                    } else {
                        //新增记录失败之后再手动删除对应的记录，避免脏数据
                        etcRewardService.delete(etcReward.getId());
                        result.setCode(JSONResult.FAIL);
                        result.setMessage("奖励领取失败，请联系管理员！");
                        return result;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    result.setCode(JSONResult.FAIL);
                    result.setMessage("奖励领取失败，请联系管理员！！");
                    return result;
                }
                if (a > 0) {
                    result.setCode(JSONResult.SUCCESS);
                    return result;
                } else {
                    result.setCode(JSONResult.FAIL);
                    result.setMessage("奖励领取失败，请重试！");
                    return result;
                }

            }
        }

        if(submitRewarInfoParam.getRewardType() == null || submitRewarInfoParam.getRewardType() == 1){
            //处理激活奖励
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("productSn", submitRewarInfoParam.getProductSn());
            queryMap.put("isSearch", "1");
            queryMap.put("isReward", "1");
            EtcDevice etcDevice = orderService.queryObject(queryMap);
            result.setCode(JSONResult.SUCCESS);
            if (etcDevice == null || etcDevice.getActiveStatus() == 0) {
                jsonObject.put("state", "0");
                result.setData(jsonObject);
                result.setMessage("设备未激活");
                return result;
            }
            Map<String, Object> q = new HashMap<>();
            q.put("deleteFlag", "0");
            q.put("productSn", submitRewarInfoParam.getProductSn());
            q.put("rewardType", "1");
            List<EtcReward> list = etcRewardService.queryList(q);
            if (CollectionUtils.isNotEmpty(list)) {
                EtcReward etcReward = list.get(0);
                if (etcReward != null && etcReward.getStatus() != 0) {
                    result.setCode(JSONResult.FAIL);
                    result.setData(etcReward);
                    result.setMessage("该红包已经被" + etcReward.getNickname() + "领取，有疑问请联系管理员！");
                    return result;
                }
            } else {
                int a = 0;
                try {
                    //通过系统配置信息判断激活奖励红包是否失效，失效时间以产品激活时间之后15天内有效
                    Date d = new Date();
                    Long longTime = d.getTime();
                    SysConfig sysConfig = sysConfigService.queryByKey("active_reward_effective_time");
                    if(etcDevice.getActiveTime() != null && sysConfig != null && sysConfig.getConfigKey() != null && Integer.valueOf(sysConfig.getConfigValue()) > 0){
                        if(longTime - etcDevice.getActiveTime().getTime() >= 60*60*24*1000*Long.valueOf(sysConfig.getConfigValue())){
                            jsonObject.put("state", 0);
                            result.setData(jsonObject);
                            result.setMessage("ETC激活后超过" + sysConfig.getConfigValue() + "天未领取，该红包已失效！");
                            result.setCode(JSONResult.FAIL);
                            return result;
                        }
                    }
                    //转账金额
                    Double amount = 0.0;
                    if (etcDevice.getMaxAmount().intValue() == etcDevice.getMinAmount()) {
                        amount = DateUtil.formatFee2Yuan(etcDevice.getMinAmount());
                    }
                    //如果区间上下限值不同则取区间随机数
                    if (etcDevice.getMaxAmount().intValue() != etcDevice.getMinAmount()) {
                        int min = etcDevice.getMinAmount(), max = etcDevice.getMaxAmount();
                        amount = DateUtil.formatFee2Yuan(min + (int) (Math.random() * (max - min + 1)));
                    }
                    //首先插入一条为付款的数据
                    Date date = new Date();
                    EtcReward etcReward = new EtcReward();
                    etcReward.setPayAmount(DateUtil.formatYuan2Fen(amount));
                    etcReward.setId(Sequence.getId());
                    etcReward.setCity(submitRewarInfoParam.getCity());
                    etcReward.setCountry(submitRewarInfoParam.getCountry());
                    etcReward.setProvince(submitRewarInfoParam.getProvince());
                    etcReward.setSubscribe(1);
                    etcReward.setStatus(1);
                    etcReward.setPayStatus(0);
                    etcReward.setLanguage("zh_CN");
                    etcReward.setDeleteFlag(0);
                    etcReward.setRewardType(1);
                    //使用OBU设备的记录ID作为商户订单号
                    etcReward.setOrderId(etcDevice.getId());
                    etcReward.setSubscribeTime(date);
                    etcReward.setUpdatedTime(etcReward.getUpdatedTime());
                    etcReward.setName(submitRewarInfoParam.getName());
                    etcReward.setPhone(submitRewarInfoParam.getPhone());
                    etcReward.setNickname(submitRewarInfoParam.getNickname());
                    etcReward.setSex(submitRewarInfoParam.getSex());
                    etcReward.setStoreAddress(submitRewarInfoParam.getStoreAddress());
                    etcReward.setOpenid(submitRewarInfoParam.getOpenid());
                    etcReward.setUnionid(submitRewarInfoParam.getUnionid());
                    etcReward.setHeadimgurl(submitRewarInfoParam.getHeadimgurl());
                    etcReward.setProductSn(submitRewarInfoParam.getProductSn());
                    etcReward.setCreateTime(date);
                    etcReward.setUpdatedTime(date);
                    etcReward.setRequestData("");
                    etcReward.setRequestData(JSON.toJSONString(etcReward));
                    a = etcRewardService.save(etcReward);
                    if (a > 0) {
                        //插入未付款数据之后开始付款
                        CorpPaymentResult corpPaymentResult = null;
                        try {
                            log.info(JSON.toJSONString(etcReward));
                            corpPaymentResult = sendCorpPayment(etcDevice, etcReward);
                            if (corpPaymentResult != null) {
                                log.info(JSON.toJSONString(corpPaymentResult));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            etcReward.setJsonData(e.getMessage());
                        }
                        //付款失败之后把记录状态改成支付失败，后面允许再次支付
                        if (corpPaymentResult == null) {
                            etcReward.setPayStatus(3);
                            etcReward.setUpdatedTime(new Date());
                        } else if (corpPaymentResult != null && corpPaymentResult.getTransactionId() != null) {
                            //微信付款成功之后改变记录的支付状态，同时更新记录的其他信息
                            etcReward.setPaymentTime(DatetimeUtil.parseSQLDate(corpPaymentResult.getPaymentTime(), DatetimeUtil.STANDARD_DATETIME_PATTERN));
                            etcReward.setPaymentNo(corpPaymentResult.getTransactionId());
                            etcReward.setPayStatus(2);
                            etcReward.setJsonData(JSON.toJSONString(corpPaymentResult));
                            etcReward.setUpdatedTime(new Date());
                            JSONObject json = JSON.parseObject(JSON.toJSONString(corpPaymentResult));
                            json.put("payAmount", etcReward.getPayAmount());
                            result.setData(json);
                        } else {
                            //支付失败之后把记录状态改成支付失败，后面允许再次支付
                            etcReward.setJsonData(JSON.toJSONString(corpPaymentResult));
                            etcReward.setPayStatus(3);
                            etcReward.setUpdatedTime(new Date());
                            result.setData(corpPaymentResult);
                        }
                        //更新记录信息
                        a = etcRewardService.update(etcReward);
                    } else {
                        //新增记录失败之后再手动删除对应的记录，避免脏数据
                        etcRewardService.delete(etcReward.getId());
                        result.setCode(JSONResult.FAIL);
                        result.setMessage("奖励领取失败，请联系管理员！");
                        return result;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    result.setCode(JSONResult.FAIL);
                    result.setMessage("奖励领取失败，请联系管理员！！");
                    return result;
                }
                if (a > 0) {
                    result.setCode(JSONResult.SUCCESS);
                    return result;
                } else {
                    result.setCode(JSONResult.FAIL);
                    result.setMessage("奖励领取失败，请重试！");
                    return result;
                }

            }
        }
        return result;
    }


    public CorpPaymentResult sendCorpPayment(EtcDevice etcDevice, EtcReward etcReward) throws Exception{
        //转账描述
        String desc = "红包奖励";
        //调用接口的机器Ip地址
        String clientIp = PayUtil.getLocalIp();
        WeixinPayAccount weixinPayAccount = new WeixinPayAccount(appId, wxPayAppSecret, wxPayMchId);
        WeixinPayProxy weixinPayProxy = new WeixinPayProxy(weixinPayAccount);

        CorpPayment corpPayment = new CorpPayment(etcReward.getOrderId(), etcReward.getOpenid(), CorpPaymentCheckNameType.NO_CHECK, desc, DateUtil.formatFee2Yuan(etcReward.getPayAmount()), clientIp);
        log.info(JSON.toJSONString(corpPayment));
        CorpPaymentResult corpPaymentResult = weixinPayProxy.sendCorpPayment(corpPayment);
        log.info(JSON.toJSONString(corpPaymentResult));
        if (corpPaymentResult != null && StringUtils.isNotEmpty(corpPaymentResult.getTransactionId())) {
            //转账成功之后的代码逻辑
            return corpPaymentResult;
        } else {
            //转账失败之后的代码逻辑
            return corpPaymentResult;
        }
    }


    /**
     * 2.1.1ETC通行单查询接口
     *
     * @return
     */
    @ApiVersion(1)
    @PostMapping("/queryDeductionRecordDetailNew")
    @ApiOperation(value = "2.1.1ETC通行单查询接口")
    public JsonResult queryDeductionRecordDetailNew(@RequestBody QueryDeductionRecordDetailNewRequest req) {
        JsonResult result = new JsonResult();
        log.info("2.1.1ETC通行单查询接口:{}", JSON.toJSONString(req));
        String data = null;
        req.setClientKey(userProperty.getClientNo());
        req.setAccessNo(userProperty.getOptBy());
        req.setSig(signature0);
        try {
            // 响应模型
            @Cleanup
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            StringBuilder sb = new StringBuilder(200);
            sb.append(JSON.toJSONString(req));

            // 创建Post请求
            HttpPost httpPost = new HttpPost("");

            StringEntity entity = new StringEntity(sb.toString(),
                    ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
            httpPost.setEntity(entity);

            /*RequestConfig config =  RequestConfig.custom().setSocketTimeout(6000)
                    .setConnectTimeout(6000).build();
            httpPost.setConfig(config);*/

            // 由客户端执行(发送)Post请求
            @Cleanup
            CloseableHttpResponse response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null && response.getStatusLine().getStatusCode() == 200) {
                String text = EntityUtils.toString(responseEntity);
                log.info("2.1.1ETC通行单查询接口,响应:{}", text);
                JSONObject jsonObject = JSON.parseObject(text);
            }
        } catch (Exception e) {
            log.error("2.1.1ETC通行单查询接口请求失败", e);
            throw new RuntimeException(e);
        }
        return result;
    }

    @ApiVersion(1)
    @PostMapping(value = "/clientStatus")
    @ApiOperation(value = "获取clientStatus信息")
    public JsonResult clientStatus() {
        JsonResult result = new JsonResult();
        result.setCode(JSONResult.SUCCESS);
        result.setMessage("SUCCESS");
        return result;
    }
}
